package com.gongpingjialoan.activity.loans;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.LoanEnumsData;
import com.gongpingjialoan.bean.VipBuycarBean;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.JSONUtil;
import com.gongpingjialoan.utility.LoanUtil;
import com.gongpingjialoan.view.LoanCarModelItemView;
import com.gongpingjialoan.view.ProgressView;
import com.gongpingjialoan.view.SelectLoanInfoDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.alibaba.sdk.android.feedback.impl.FeedbackAPI.mContext;
import static com.gongpingjialoan.R.id.house;
import static com.gongpingjialoan.R.id.income;
import static com.gongpingjialoan.R.id.profession;

/**
 * 完善信息
 */
public class ImprovementInformationActivity extends BaseActivity implements View.OnClickListener {
    private ProgressView mProgressView;
    private TextView professionT, incomeT, houseT, submitT, current_priceT;
    private LoanEnumsData professionData;
    private LoanEnumsData incomeData;
    private LoanEnumsData houseData;
    private LoanCarModelItemView car_mode_layout;

    List<LoanEnumsData> professions_list = new ArrayList<>();
    List<LoanEnumsData> incomes_list = new ArrayList<>();
    List<LoanEnumsData> house_types_list = new ArrayList<>();

    //当前职业额度
    private int current_professions = 0, max_progress = 500000;
    //当前月收入比率 //当前住房比率
    private float current_incomes = 0, current_house_types = 0;

    //根据问卷选项算出后的价格
    private int current_loan_price = 0;

    //最小额度
    private final float MIN_PAYMENT = 50000;
    //最大额度
    private final float MEDIUM_PAYMENT = 100000;
    private java.text.DecimalFormat df;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_improvement_information);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanQuestionnaireView);
        setTitle("完善信息");
        setRightImage(R.drawable.kefu_phone, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanQuestionnaireService);
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4000253500"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        df = new java.text.DecimalFormat("##,###,###");
        professionT = (TextView) findViewById(profession);
        incomeT = (TextView) findViewById(income);
        houseT = (TextView) findViewById(house);
        submitT = (TextView) findViewById(R.id.submit);
        current_priceT = (TextView) findViewById(R.id.current_price);
        car_mode_layout = (LoanCarModelItemView) findViewById(R.id.car_mode_layout);

        professionT.setOnClickListener(this);
        incomeT.setOnClickListener(this);
        houseT.setOnClickListener(this);
        submitT.setOnClickListener(this);

        professionT.setEnabled(false);
        incomeT.setEnabled(false);
        houseT.setEnabled(false);

        professionT.addTextChangedListener(new MyTextWatcher());
        incomeT.addTextChangedListener(new MyTextWatcher());
        houseT.addTextChangedListener(new MyTextWatcher());
        initProgress();
        getEvaluationsEnums();
    }

    private void initProgress() {

//        current_priceT.setText(df.format(MIN_PAYMENT) + "");
        mProgressView = (ProgressView) findViewById(R.id.progressView);
        mProgressView.setStrokeWidth(30);
        mProgressView.setStartAngle(135);
        mProgressView.setMaxAngle(270);
//        mProgressView.animProgress(0.2f);

        setCurrentPriceText();
    }

    //刷新页面当前可贷额度 进度条
    private void setCurrentPriceText(){
        int current_price = LoanUtil.computingAmount(current_loan_price,car_mode_layout.getCarPrice());
        java.text.DecimalFormat df = new java.text.DecimalFormat("##,###,###");
        current_priceT.setText(df.format(current_price));

        float progress;
        if (current_price <= MIN_PAYMENT) {
            progress = 0.2f;
        } else if (current_price <= MEDIUM_PAYMENT) {
            progress = 0.3f;
        } else {
            progress = 0.3f + (((float) current_price - MEDIUM_PAYMENT) / ((float) max_progress - MEDIUM_PAYMENT)) * 0.7f;
        }
        mProgressView.animProgress(progress);
    }

    /**
     * 计算问卷选项部分可贷额度
     */
    private void setProgress() {
        BigDecimal b1 = new BigDecimal(current_professions + "");

//        BigDecimal b2 = new BigDecimal(current_house_types * current_incomes + "");
        BigDecimal b3 = new BigDecimal(current_house_types + "");
        BigDecimal b4 = new BigDecimal(current_incomes + "");
        BigDecimal b5 = new BigDecimal(b3.multiply(b4).doubleValue()+"");
        current_loan_price = new BigDecimal(b1.multiply(b5).floatValue() + "").setScale(2, BigDecimal.ROUND_HALF_UP).intValue();
        //调整问卷选项后刷新当前额度
        setCurrentPriceText();
    }

    @Override
    public void onClick(View v) {
        SelectLoanInfoDialog dialog;
        switch (v.getId()) {
            case R.id.profession:
                dialog = new SelectLoanInfoDialog(mySelf, "选择职业", professions_list, new SelectLoanInfoDialog.OnDialogCallBack() {
                    @Override
                    public void onDateBack(int currentItem) {
                        professionData = professions_list.get(currentItem);
                        professionT.setText(professionData.getName());
                        current_professions = professionData.getAmount();
                        setProgress();
                    }
                });
                dialog.show();
                break;
            case R.id.income:
                if (TextUtils.isEmpty(professionT.getText())) {
                    showTips(0, "请先选择您的职业");
                    return;
                }
                dialog = new SelectLoanInfoDialog(mySelf, "选择收入范围", incomes_list, new SelectLoanInfoDialog.OnDialogCallBack() {
                    @Override
                    public void onDateBack(int currentItem) {
                        incomeData = incomes_list.get(currentItem);
                        incomeT.setText(incomeData.getName());
                        current_incomes = incomeData.getRate();
                        setProgress();
                    }
                });
                dialog.show();
                break;
            case R.id.house:
                if (TextUtils.isEmpty(professionT.getText())) {
                    showTips(0, "请先选择您的职业");
                    return;
                }
                dialog = new SelectLoanInfoDialog(mySelf, "选择住房类型", house_types_list, new SelectLoanInfoDialog.OnDialogCallBack() {
                    @Override
                    public void onDateBack(int currentItem) {
                        houseData = house_types_list.get(currentItem);
                        houseT.setText(houseData.getName());
                        current_house_types = houseData.getRate();
                        setProgress();
                    }
                });
                dialog.show();
                break;
            case R.id.submit:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.QuestionaryApplyClick);
                submit();
                break;
            default:
                break;
        }
    }

    private void submit() {
        PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanQuestionnaireCommit);
        showProgressDialog();
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                hidenProgressDialog();
                Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                hidenProgressDialog();
                try {
                    JSONObject jo = new JSONObject(json);
                    if (jo == null) {
                        return;
                    }
                    if ("error".equals(jo.getString("status"))) {
                        Toast.makeText(mySelf, jo.getString("msg"), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    LoanUtil.toLoanData(json);
                    LoanUtil.goToPerfect(mySelf);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 1);

        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.perfect_evaluations);
        netDataJson.setUseOtherDomain(true);
        netDataJson.addParam("step", "questionnaire");
        netDataJson.addParam("profession", professionData.getKey());
        netDataJson.addParam("house_type", houseData.getKey());
        netDataJson.addParam("income", incomeData.getKey());
        netDataJson.request("put");
    }

    // 选择完车型后,调用这辆
    @Subscribe
    public void onEventMainThread(VipBuycarBean vipBuycarBean) {
        PointRecordManage.getInstance().addPoint(mySelf, Piont.QuestionaryChooseClick);
        car_mode_layout.onBrandSelceted(vipBuycarBean);
        //更换车型后刷新额度
        setCurrentPriceText();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private class MyTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            isReady();
        }
    }

    //监听所有数据填满 才可以点击提交
    public void isReady() {
        submitT.setBackgroundResource(R.color.text_grey_dark);
        submitT.setEnabled(false);

        if (TextUtils.isEmpty(professionT.getText().toString())) {
            return;
        }
        if (TextUtils.isEmpty(incomeT.getText().toString())) {
            return;
        }
        if (TextUtils.isEmpty(houseT.getText().toString())) {
            return;
        }

        submitT.setBackgroundResource(R.color.blue_3fbbff);
        submitT.setEnabled(true);
    }

    private void getEvaluationsEnums() {
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                try {
                    JSONObject jo = new JSONObject(json);
                    if (jo == null) {
                        return;
                    }
                    if ("error".equals(jo.getString("status"))) {
                        Toast.makeText(mContext, jo.getString("msg"), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    JSONObject data_jo = JSONUtil.getJSONObject(jo, "data");
                    if (data_jo != null) {
                        professionT.setEnabled(true);
                        incomeT.setEnabled(true);
                        houseT.setEnabled(true);

                        JSONObject professions_jo = JSONUtil.getJSONObject(data_jo, "professions");
                        JSONObject incomes_jo = JSONUtil.getJSONObject(data_jo, "incomes");
                        JSONObject house_types_jo = JSONUtil.getJSONObject(data_jo, "house_types");

                        for (int i = 0; i < professions_jo.length(); i++) {
                            String key = i + 1 + "";
                            JSONObject key_jo = JSONUtil.getJSONObject(professions_jo, key);
                            int amount = JSONUtil.getInt(key_jo, "amount");
                            LoanEnumsData data = new LoanEnumsData();
                            data.setKey(key);
                            data.setName(JSONUtil.getString(key_jo, "name"));
                            data.setAmount(amount);
                            professions_list.add(data);

                            if (max_progress < amount) {
                                max_progress = amount;
                            }
                            if (i == 0) {
                                current_professions = amount;
                            }
                            if (current_professions > amount) {
                                current_professions = amount;
                            }
                        }

                        for (int i = 0; i < incomes_jo.length(); i++) {
                            String key = i + 1 + "";
                            JSONObject key_jo = JSONUtil.getJSONObject(incomes_jo, key);
                            float rate = JSONUtil.getFloat(key_jo, "rate");
                            LoanEnumsData data = new LoanEnumsData();
                            data.setKey(key);
                            data.setName(JSONUtil.getString(key_jo, "name"));
                            data.setRate(rate);
                            incomes_list.add(data);

                            if (i == 0) {
                                current_incomes = rate;
                            }
                            if (current_incomes > rate) {
                                current_incomes = rate;
                            }
                        }

                        for (int i = 0; i < house_types_jo.length(); i++) {
                            String key = i + 1 + "";
                            JSONObject key_jo = JSONUtil.getJSONObject(house_types_jo, key);
                            float rate = JSONUtil.getFloat(key_jo, "rate");
                            LoanEnumsData data = new LoanEnumsData();
                            data.setKey(key);
                            data.setName(JSONUtil.getString(key_jo, "name"));
                            data.setRate(rate);
                            house_types_list.add(data);

                            if (i == 0) {
                                current_house_types = rate;
                            }
                            if (current_house_types > rate) {
                                current_house_types = rate;
                            }
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 1);

        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.evaluations_enums);
        netDataJson.setUseOtherDomain(true);
        netDataJson.request("get");
    }

    @Override
    public void finish() {
        super.finish();
        PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanQuestionnaireBack);
    }
}
